package com.itheima.stock.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @author by itheima
 * @Date 2022/1/21
 * @Description 定义范围查询命中数据库的策略
 */
public class StockRtInfoDbRangeHandler implements RangeShardingAlgorithm<Date> {
    /**
     * m-$->{2021..2022}.stock_rt_info_$->{1..12}
     * @param availableTargetNames 当前逻辑表对应的所有的库名称集合： m-2021,m-2022
     * @param shardingValue 封装了cur_time片键相关的信息
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        //获取逻辑表
        String logicTableName = shardingValue.getLogicTableName();
        //获取片键
        String columnName = shardingValue.getColumnName();
        //获取封装上限和下限的对象
        Range<Date> valueRange = shardingValue.getValueRange();

        if (valueRange.hasLowerBound()) {
            //获取下限 2020
            Date start = valueRange.lowerEndpoint();
            //获取年份
            int startYear = new DateTime(start).getYear();
            //获取出数据库名称后缀的值大于或者等于起始年的数据库名称集合
            availableTargetNames = availableTargetNames.stream().filter(dbName ->
                    Integer.valueOf(dbName.substring(dbName.lastIndexOf("-") + 1)) >= startYear
            ).collect(Collectors.toList());
        }


        if (valueRange.hasUpperBound()) {
            //获取下限 2023
            Date end = valueRange.upperEndpoint();
            //获取年份
            int endYear = new DateTime(end).getYear();
            //获取出数据库名称后缀的值小于或者等于起始年的数据库名称集合
            availableTargetNames = availableTargetNames.stream().filter(
                    dbName ->Integer.valueOf(dbName.substring(dbName.lastIndexOf("-") + 1)) <= endYear).collect(Collectors.toList());
        }

        return availableTargetNames;
    }
}